package wtws.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

public class SFTPManager {

	JSch jsch;
	Session session;

	ChannelSftp channel = null;

	private String url;
	private String username;
	private String password;

	public SFTPManager(String url, String username, String password) {
		this.url = url;
		this.username = username;
		this.password = password;
		this.jsch = new JSch();
	}

	public boolean ftpLogin() {
		try {
			session = jsch.getSession(username, url, 22);
			session.setConfig("StrictHostKeyChecking", "no");
			session.setPassword(password);
			session.connect();
			Channel chl = session.openChannel("sftp");
			chl.connect();
			channel = (ChannelSftp) chl;
		} catch (JSchException e) {
			e.printStackTrace();
		}
		return true;
	}

	public void changeDir(String path) {
		try {
			channel.cd(path);
		} catch (SftpException e) {
			e.printStackTrace();
		}
	}

	public void close() {
		channel.disconnect();
		session.disconnect();
	}

	public void downloadFile(String localFilePath, String remoteFileName) throws Exception {
		try {
			channel.get(remoteFileName, localFilePath);
			channel.rm(remoteFileName);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	@SuppressWarnings("unchecked")
	public List<String> ls(String pattern) throws Exception {
		ArrayList<String> result = new ArrayList<String>();
		Vector<LsEntry> allFiles = null;
		try {

			allFiles = channel.ls(pattern);
		} catch (SftpException e) {
			e.printStackTrace();
			throw e;
		}
		for (LsEntry entry : allFiles) {
			result.add(entry.getFilename());
		}
		return result;
	}

	public String getURL() {
		return url;
	}

	public void setURL(String uRL) {
		url = uRL;
	}

	public String getUSERNAME() {
		return username;
	}

	public void setUSERNAME(String uSERNAME) {
		username = uSERNAME;
	}

	public String getPASSWORD() {
		return password;
	}

	public void setPASSWORD(String pASSWORD) {
		password = pASSWORD;
	}

}